//
//  DefaultAlertView.swift
//  jyzx
//
//  Created by cyptt on 2022/4/29.
//

import UIKit
import SnapKit
// 1.标题 字体大小、字体颜色
// 2.内容 字体大小、字体颜色 、位置
// 3.取消按钮 字体大小、字体颜色、边框颜色
// 4.确定安装 字体大小、字体颜色、边框颜色
// 5.右边叉叉按钮是否显示
public class CHDefaultAlertView: CHKeyBoardView,UITextFieldDelegate {

    public enum Position : Int {
        case center = 0
        case left = 1
    }
    
    public var textFields:[UITextField] = []
    public var textLables:[UILabel] = []
    public var textLines:[UIView] = []
    public var chaImage:UIImage?
    public var actions:[CHAlertAction] = []
    public var margin_B:CGFloat = 24    //按钮距离底部边距
    
    public var bottomBtn_H:CGFloat = 44
    //lineviewcolor
    private let bottomLineColor:UIColor = UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
//    public  var bottomLineColor:UIColor?{
//        get {
//            return _bottomLineColor
//        }
//        set {
//            _bottomLineColor = newValue ?? UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
//        }
//    }
    
    //取消按钮字体颜色
    var _cancelTitleColor:UIColor = UIColor.init(red: 119/255.0, green: 122/255.0, blue: 126/255.0,alpha: 1)
    public  var cancelTitleColor:UIColor?{
        get {
            return _cancelTitleColor
        }
        set {
            _cancelTitleColor = newValue ?? UIColor.init(red: 119/255.0, green: 122/255.0, blue: 126/255.0,alpha: 1)
        }
    }
    
    //取消按钮边框颜色
    var _cancelBorderColor:UIColor = UIColor.init(red: 166/255.0, green: 170/255.0, blue: 178/255.0,alpha: 1)
    public var cancelBorderColor:UIColor?{
        get {
            return _cancelBorderColor
        }
        set {
            _cancelBorderColor = newValue ?? UIColor.init(red: 166/255.0, green: 170/255.0, blue: 178/255.0,alpha: 1)
        }
    }
    
    // 取消按钮边框
    var _cancelBorderW:CGFloat =  0.5
    public var cancelBorderW:CGFloat?{
        get {
            return _cancelBorderW
        }
        set {
            _cancelBorderW = newValue ?? 0.5
        }
    }
    
    //按钮字体
    var _butttonFont:UIFont =  UIFont.systemFont(ofSize: 17)
    public var butttonFont:UIFont?{
        get {
            return _butttonFont
        }
        set {
            _butttonFont = newValue ??  UIFont.systemFont(ofSize: 17)
        }
    }
    
    var _sureTitleColor:UIColor = UIColor.white
    public  var sureTitleColor:UIColor?{
        get {
            return _sureTitleColor
        }
        set {
            _sureTitleColor = newValue ?? UIColor.white
        }
    }
    
    // 圆角大小
    var _btnCornerRadius:CGFloat = 10
    public  var btnCornerRadius:CGFloat?{
        get {
            return _btnCornerRadius
        }
        set {
            _btnCornerRadius = newValue ??  10
        }
    }
    
    //确定按钮背景颜色
    var _sureBtnColor:UIColor = UIColor.init(red: 56/255.0, green: 119/255.0, blue: 244/255.0, alpha: 1)
    public var sureBtnColor:UIColor?{
        get {
            return _sureBtnColor
        }
        set {
            _sureBtnColor = newValue ?? UIColor.init(red: 56/255.0, green: 119/255.0, blue: 244/255.0, alpha: 1)
        }
    }
    
    //取消按钮边框颜色
    var _textFBorderColor:UIColor = UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
    public var textFBorderColor:UIColor?{
        get {
            return _textFBorderColor
        }
        set {
            _textFBorderColor = newValue ?? UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
        }
    }
    
    //输入框圆角大小
    var _textFCornerRadius:CGFloat = 10
    public var textFCornerRadius:CGFloat?{
        get {
            return _textFCornerRadius
        }
        set {
            _textFCornerRadius = newValue ??  10
        }
    }
    
    //输入框边框宽度
    var _textFBorderW:CGFloat =  0.5
    public  var textFBorderW:CGFloat?{
        get {
            return _textFBorderW
        }
        set {
            _textFBorderW = newValue ?? 0.5
        }
    }
    
    /*
     下划线颜色
     */
    var _textLineColor:UIColor = UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
    
    public  var textLineColor:UIColor?{
        get {
            return _textLineColor
        }
        set {
            _textLineColor = newValue ?? UIColor.init(red: 216/255.0, green: 216/255.0, blue: 216/255.0,alpha: 1)
        }
    }
    
    /*
     是否显示下划线 true  显示下划线 false默认显示圆角
     */
    var _isShowTextLine:Bool = false
    
    public  var isShowTextLine:Bool?{
        get {
            return _isShowTextLine
        }
        set {
            _isShowTextLine = newValue ?? false
        }
    }
    
   
    private var DefaultH = 166   //只有按钮 + 标题高度
    private let marginL_R = 20   //距离左右边距

    private var content_Margin_T = 80 //第一个内容距离顶部距离
    private let mwindow:UIWindow = UIApplication.shared.keyWindow!
    private let My_TAG = 3000

    private  let defaultGrayColor:UIColor = UIColor.init(red: 166/255.0, green: 170/255.0, blue: 178/255.0,alpha: 1)

//    private let sureBlueColor:UIColor = UIColor.init(red: 56/255.0, green: 119/255.0, blue: 244/255.0, alpha: 1)
    
    private var messageL_H:CGFloat = 0
  
    
    //内容字体大小
    private var _defaultMsgFontSize:CGFloat = 14
    private var defaultMsgFontSize:CGFloat?{
        get {
            return _defaultMsgFontSize
        }
        set {
            _defaultMsgFontSize = newValue ?? 14
        }
    }
    

     
    /*
     view加载到window 上面
     */
    public func show(title:String?,msg:String?,attributes: [NSAttributedString.Key : Any]? = nil,controller:UIViewController? = nil){
        DefaultH = DefaultH + Int(self.margin_B)
        if controller == nil{
            mwindow.addSubview(self)
        }else{
            controller!.view.addSubview(self)
        }
     
        self.showTitle(title:title)
        self.showMessageL(msg: msg,attributes: attributes)
    
        self.showTextF()
        
        
        
        self.actionShow()
    }
    

    public func hide(){
        self.removeFromSuperview()
    }
    
    /*
     添加点击事件
     */
   public func addAction(_ action: CHAlertAction){
        self.actions.append(action)
    }
    /*
     设置关闭按钮图片
     */
    public func setChaImage(image:UIImage?){
        self.chaImage = image
        self.chaBtn.setImage(image ?? UIImage.init(named: ""), for: UIControl.State.normal)
      
    }
    
    /*
     插按钮回调
     */
    var chaCallback:(() -> ())?
    public func addChaCallback(closure:@escaping()-> Void){
        self.chaCallback = closure
    }
    /*
     设置标题颜色
     */
    public  func setTitleColor(color:UIColor){
        self.titleL.textColor = color
    }
    
    /*
     设置标题字体
     */
    public func setTitleFont(font:UIFont){
        self.titleL.font = font
    }
    
    /*
     设置内容颜色
     */
    public func setMessageColor(color:UIColor){
        self.messageL.textColor = color
    }
    
    /*
     设置内容位置
     */
    public  func setMessagePisition(position:NSTextAlignment){
        self.messageL.textAlignment  = position
    }
    

    /*
     设置内容字体大小
     */
    public func setMessageFont(font:UIFont){
    
        self.defaultMsgFontSize = font.pointSize
        self.messageL.font = font
    }
    
    /*
     设置背景圆角大小
     */
    public func setContentCornerRadius(cor:CGFloat){
        self.contentV.layer.cornerRadius = cor
    }
    
    /*
     设置底部线条颜色
     */
    public func setBottomLineView(color:UIColor){
        self.bottomLineView.backgroundColor = color
    }
    
    /*
     设置底部线高度
     */
    public func setBottomLineViewH(height:CGFloat){
        self.bottomLineView.frame.size.height = height
    }
    
    /*
     底部是line是否隐藏
     */
    public func setLineViewisHidden(isHide:Bool){
        self.bottomLineView.isHidden = isHide
    }
    
    /**
     隐藏关闭按钮
     */
    public func hideChaBtn(){
        self.chaBtn.isHidden = true
    }
    
    private  func actionShow(){
        
    
     //判断action 个数
     if self.actions.count == 1{
         let action:CHAlertAction = self.actions.first!
         
         if action.style == CHAlertAction.Style.cancel {
             let btn:UIButton = cancelBtn(action: action,tagIndex: 0)
            
             btn.snp.makeConstraints { make in
                 make.left.equalTo(self.contentV).offset(marginL_R)
                 make.bottom.equalTo(self.contentV.snp.bottom).offset(-margin_B)
                 make.right.equalTo(self.contentV).offset(-marginL_R)
                 make.height.equalTo(bottomBtn_H)
             }
         }else{
             let btn:UIButton = defaultBtn(action: action,tagIndex: 0)
             btn.snp.makeConstraints { make in
                 make.left.equalTo(self.contentV).offset(marginL_R)
                 make.right.equalTo(self.contentV).offset(-marginL_R)
                 make.bottom.equalTo(self.contentV.snp.bottom).offset(-margin_B)
                 make.height.equalTo(bottomBtn_H)
             }
         }
     }else if(self.actions.count == 2){
         //action
         var i = 0;
         for action in self.actions{
 
             var btn:UIButton = cancelBtn(action: action,tagIndex: i)
             if action.style == CHAlertAction.Style.cancel{

                 btn = cancelBtn(action: action,tagIndex: i)
             }else{
                 btn = defaultBtn(action: action,tagIndex: i)

             }

             if i == 0 {
                 btn.snp.makeConstraints { make in
                     make.right.equalTo(self.contentV.snp.centerX).offset(-10)
                     make.left.equalTo(self.contentV).offset(marginL_R)
                     make.bottom.equalTo(self.contentV.snp.bottom).offset(-margin_B)
                     make.height.equalTo(bottomBtn_H)
                 }
             }else{
                 btn.snp.makeConstraints { make in
                     make.left.equalTo(self.contentV.snp.centerX).offset(10)
                     make.right.equalTo(self.contentV).offset(-marginL_R)
                     make.bottom.equalTo(self.contentV.snp.bottom).offset(-margin_B)
                     make.height.equalTo(bottomBtn_H)
                 }
             }
            
             i = i + 1
         }
     }else{
         print("目前最多支持两个按钮")
     }
    
    }
    
    
    
    /*
     取消按钮
     */
    private  func cancelBtn(action:CHAlertAction,tagIndex:Int)->UIButton{
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setTitle(action.title, for:  UIControl.State.normal)
        btn.setTitleColor(self.cancelTitleColor, for: UIControl.State.normal)
        btn.layer.cornerRadius = self.btnCornerRadius!
        btn.layer.masksToBounds = true
        btn.layer.borderColor = self.cancelBorderColor!.cgColor
        btn.layer.borderWidth = self.cancelBorderW!
        btn.tag = My_TAG + tagIndex
        btn.titleLabel?.font = self.butttonFont!
        btn.addTarget(self, action: #selector(btnClick(btn:)), for: UIControl.Event.touchUpInside)
        self.contentV.addSubview(btn)
        return btn
    }
    
    /*
     正常按钮
     */
    private  func defaultBtn(action:CHAlertAction,tagIndex:Int)->UIButton{
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setTitle(action.title, for:  UIControl.State.normal)
        btn.setTitleColor(self.sureTitleColor, for: UIControl.State.normal)
        btn.backgroundColor = self.sureBtnColor!
        btn.layer.cornerRadius = self.btnCornerRadius!
        btn.layer.masksToBounds = true
        btn.tag = My_TAG + tagIndex
        btn.titleLabel?.font = self.butttonFont!
        btn.addTarget(self, action: #selector(btnClick(btn:)), for: UIControl.Event.touchUpInside)
        self.addSubview(btn)
        return btn
    }
   private func showTextF(){
        //textf
        var i = 0
       var itemH:CGFloat = 50
       if self.textLables.count > 0{
           itemH = 90
           content_Margin_T = 70 + 15
           DefaultH = 160 + 15
           for textF in self.textFields{
               var marginMessage = 0
               if messageL_H > 0{
                   marginMessage = 20
               }
               let label = self.textLables[i]
              
               
               label.snp.makeConstraints { make in
                   make.left.equalTo(self.contentV).offset(marginL_R)
                   make.right.equalTo(self.contentV).offset(-marginL_R)
                   make.top.equalTo(self.contentV).offset(content_Margin_T + Int(messageL_H) + marginMessage + Int(itemH) * i)
                  
               }
               
               textF.snp.makeConstraints { make in
                   make.left.equalTo(self.contentV).offset(marginL_R)
                   make.right.equalTo(self.contentV).offset(-marginL_R)
                   make.top.equalTo(label.snp.bottom).offset(12)
                   make.height.equalTo(40)
               }
               
               
               i = i + 1
           }
       }else{
           itemH = 50
           for textF in self.textFields {
               var marginMessage = 0
               if messageL_H > 0{
                   marginMessage = 20
               }
               textF.snp.makeConstraints { make in
                   make.left.equalTo(self.contentV).offset(marginL_R)
                   make.right.equalTo(self.contentV).offset(-marginL_R)
                   make.top.equalTo(self.contentV).offset(content_Margin_T + Int(messageL_H) + marginMessage + 50 * i)
                   make.height.equalTo(40)
               }
               i = i + 1
           }
           
       }
       
       var j = 0
       if self.isShowTextLine == true{
           for textF in self.textFields {
               let lineV = self.textLines[j]
               lineV.snp.makeConstraints { make in
                   make.left.equalTo(self.contentV).offset(marginL_R)
                   make.right.equalTo(self.contentV).offset(-marginL_R)
                   make.height.equalTo(0.5)
                   make.top.equalTo(textF.snp.bottom).offset(-0.5)
               }
               j = j + 1
           }
       }
      
        self.contentV.snp.makeConstraints { make in
            make.height.equalTo(DefaultH  + Int(messageL_H) + Int(itemH)*i)
            make.center.equalTo(self.center)
            make.width.equalTo(Int(self.frame.size.width) - 2*marginL_R)
        }
    }
    
    
    
   private func showTitle(title:String?){
       if title != nil {
           self.titleL.text = title
           if title! != ""{
               
           }else{
               DefaultH =  DefaultH - 20
               content_Margin_T = content_Margin_T - 20 //缩进20
           }
       }else{
           DefaultH =  DefaultH - 20
           content_Margin_T = content_Margin_T - 20 //缩进20
       }
     
    }
    private func showMessageL(msg:String?,attributes: [NSAttributedString.Key : Any]? = nil){
//        if self.textFields.count > 0{
//            content_Margin_T = 70
//        }
        //计算messagel 高度
    
        if msg == "" || msg == nil{
            messageL_H = 0
        }else {
            messageL_H = labelHeight(width: self.contentV.frame.size.width - CGFloat(2 * marginL_R), fontSize: self.defaultMsgFontSize!, text: msg!,attributes: attributes)
            print(messageL_H)
            
            var attributedText:NSMutableAttributedString? = NSMutableAttributedString(string: msg!)
            
            if attributes != nil{
                let range = NSRange(location: 0, length: attributedText?.length ?? 0)
                attributedText?.addAttributes(attributes!, range: range)
          
              
                attributedText?.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: self.defaultMsgFontSize!),range: range)
        
       
                self.messageL.attributedText = attributedText
                
            }else{
                self.messageL.text = msg
            }
   
        }
    
        
        
        self.messageL.snp.makeConstraints { make in
            make.left.equalTo(self.contentV).offset(marginL_R)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.top.equalTo(self.contentV).offset(content_Margin_T)
            make.height.equalTo(messageL_H)
        }
    }
   
  
   
    override init(frame:CGRect){
        super.init(frame: frame)
        print(frame)
        if frame == CGRect.zero {
            print("进来了")
            self.frame = mwindow.bounds
        
        }else{
         
        }
        
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
        
        self.addSubview(self.contentV)
     
        
        self.setPosition()
        
    }
    
    /*
     添加textf
     */
    public func addTextField(configurationHandler: ((UITextField) -> Void)? = nil){
    
        //下划线
        if self.isShowTextLine == true{
            let lineView:UIView = UIView()
            lineView.backgroundColor = self.textLineColor
            self.contentV.addSubview(lineView)
            textLines.append(lineView)
        }
        let textF:UITextField = UITextField()
        self.contentV.addSubview(textF)
        textF.returnKeyType =  UIReturnKeyType.done
        textF.delegate = self
        textF.font = UIFont.systemFont(ofSize: 14)
        
        if self.isShowTextLine == false{
            textF.layer.cornerRadius = self.textFCornerRadius!
            textF.layer.masksToBounds = true
            textF.layer.borderWidth = self.textFBorderW!
            textF.layer.borderColor = self.textFBorderColor!.cgColor
            //        textF.setValue(3, forKey: "paddingLeft") //这样设置光标移动了 placeholder没有移动
            textF.leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 8, height: 10))
        }
   
    
        textF.leftViewMode = UITextField.ViewMode.always
        textFields.append(textF)
        if  configurationHandler != nil {
            configurationHandler!(textF)
        }
    }
    
    public func addTextField(configurationHandler: ((UITextField,UILabel) -> Void)? = nil){
        
        let label:UILabel = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.init(red: 84/255.0, green: 87/255.0, blue: 94/255.0, alpha: 1)
        self.contentV.addSubview(label)
        textLables.append(label)
        
        //下划线
        if self.isShowTextLine == true{
            let lineView:UIView = UIView()
            lineView.backgroundColor = self.textLineColor
            self.contentV.addSubview(lineView)
            textLines.append(lineView)
        }
        
        let textF:UITextField = UITextField()
        self.contentV.addSubview(textF)
        textF.returnKeyType =  UIReturnKeyType.done
        textF.delegate = self
        textF.font = UIFont.systemFont(ofSize: 14)
        
        if self.isShowTextLine == false{
            textF.layer.cornerRadius = self.textFCornerRadius!
            textF.layer.masksToBounds = true
            textF.layer.borderWidth = self.textFBorderW!
            textF.layer.borderColor = self.textFBorderColor!.cgColor
//            textF.setValue(3, forKey: "paddingLeft") //这样设置光标移动了 placeholder没有移动
            textF.leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 8, height: 10))
        }
 
      
      
        textF.leftViewMode = UITextField.ViewMode.always
        textFields.append(textF)
        if  configurationHandler != nil {
            configurationHandler!(textF,label)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setPosition(){
        self.titleL.snp.makeConstraints { make in
            make.top.equalTo(self.contentV).offset(20)
            make.centerX.equalTo(self.contentV)

        }
        self.chaBtn.snp.makeConstraints { make in
            make.centerY.equalTo(self.titleL)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.width.height.equalTo(20)
        }
     
        self.bottomLineView.snp.makeConstraints { make in
            make.height.equalTo(0.5)
            make.width.equalTo(self)
            make.bottom.equalTo(self.contentV).offset(-bottomBtn_H-margin_B)
            make.left.equalTo(self.contentV)
        }
       
   
    }
    
    lazy var contentV = {()-> UIView in
    
        let contentV:UIView = UIView.init(frame: CGRect.init(x: marginL_R, y: 0, width: Int(self.frame.size.width) - 2*marginL_R, height: DefaultH))
        contentV.center = self.center
        contentV.layer.masksToBounds = true
        contentV.layer.cornerRadius = 10
        contentV.backgroundColor = UIColor.white
        contentV.addSubview(self.titleL)

        contentV.addSubview(self.messageL)
        contentV.addSubview(self.chaBtn)
        contentV.addSubview(self.bottomLineView)
        return contentV
    }()
    
    lazy var titleL = {()-> UILabel in
    
        let label:UILabel = UILabel()
        label.text = "标题"
        label.font = UIFont.systemFont(ofSize: 16,weight: UIFont.Weight.bold)
        label.textColor = UIColor.init(red: 35/255.0, green: 41/255.0, blue: 51/255.0, alpha: 1)
   
        return label
    }()
    lazy var messageL = {()-> UILabel in
    
        let label:UILabel = UILabel()
        label.text = ""
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.left
        label.font = UIFont.systemFont(ofSize: self.defaultMsgFontSize! )
        label.textColor = UIColor.init(red: 35/255.0, green: 41/255.0, blue: 51/255.0, alpha: 1)
        label.lineBreakMode = NSLineBreakMode.byCharWrapping
   
        return label
    }()
    
    lazy var chaBtn = {()-> UIButton in
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(self.chaImage ?? UIImage.init(named: "captcha_refresh_close"), for: UIControl.State.normal)

        btn.addTarget(self, action: #selector(chaBtnClick(btn:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var bottomLineView = {()->UIView in
        let lineV:UIView = UIView()
        lineV.backgroundColor = self.bottomLineColor
        
        lineV.isHidden = true
        return lineV
    }()

    
}

//btnclick
extension CHDefaultAlertView {
    @objc func chaBtnClick(btn:UIButton){
        self.removeFromSuperview()
        if self.chaCallback != nil{
            self.chaCallback!()
        }
    }
    
    /*
     按钮点击事件
     */
    @objc func btnClick(btn:UIButton){
       

        let action:CHAlertAction = self.actions[btn.tag - My_TAG]
       
        if action.handelr != nil{
            action.handelr!(action)
        }
        if action.isClose == true{
            self.removeFromSuperview()
        }
   
    }
}

//tool
extension CHDefaultAlertView{
    func labelHeight(width:CGFloat,fontSize:CGFloat,text:String,attributes: [NSAttributedString.Key : Any]? = nil)->CGFloat{
        print("attributes---",attributes)
        var attDics:[NSAttributedString.Key : Any] = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize)]
    

      
        attributes?.forEach({ (key: NSAttributedString.Key, value: Any) in
            attDics[key] = value
        })
        print("attDics-===",attDics);
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        let rect = text.boundingRect(with: size, options: [.usesFontLeading,.usesLineFragmentOrigin], attributes: attDics, context: nil)
        return CGFloat(ceilf(Float(rect.size.height)))
    }

}
//MARK: -- UITextFieldDelegate
extension CHDefaultAlertView{
    
   public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}


